<?php

namespace App\Http\Controllers\Site;

use App\B2BProject\Custom\Business\Goods;
use App\B2BProject\Custom\Business\GoodsSpecification;
use App\B2BProject\Custom\Business\Store;
use App\B2BProject\Custom\MemberInformation;
use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\Purchaser\ShoppingCart;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ShoppingCartController extends Controller
{
    use HelperControllerBuildTrait;

    public function __construct()
    {
        parent::__construct();

        /* $this->middleware('purchaser.check', ['only' => ['postSave']]);*/
    }

    /**
     * 商品信息 添加进购物车
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function postShoppingCart(Request $request)
    {
        try {
            $validator = \Validator::make(
                $request->all(),
                [
                    'buyNum' => "required|numeric",
                ]
            );
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator);
            }
            \DB::transaction(function () use ($request) {
                $data = [];

                $data['goods_id']      = $request->input('shopId');
                $data['goods_spec_id'] = $request->input('shopSpecId');
                $data['amount']        = $request->input('buyNum');

                ShoppingCart::addToCart($data['goods_id'], $data['amount'], $data['goods_spec_id']);
            });
            return response()->json(1);

        } catch (UserTypeException $e) {
            return redirect('用户类型不匹配', '403');
            throw $e;
        }
    }

    /**
     * 获取当前用户购物车中的信息
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getCartList(Request $request)
    {
        $goods    = $request->input('goodid');
        $member   = \Auth::user();
        $shopping = ShoppingCart::where('member_id', $member->id)->first();
        try {
            //该用户购物车里有商品存在的情况下
            if (!is_null($shopping)) {
                $shoppingList = ShoppingCart::where('member_id', $member->id)->get();
                if (\Request::ajax()) {
                    $count = ShoppingCart::where('member_id', $member->id)->count();
                    $class = [];
                    $total = 0;

                    foreach ($shoppingList as $shop) {
                        //根据goods_id 查找store_id
                        $store_id = $shop->goods->store_id;

                        if (!isset($class[$store_id])) {
                            //根据store_id 查找店铺的名字
                            $company = MemberInformation::where('id',
                                Store::where('id', $store_id)->first()->member_id)->first()->company;

                            $class[$store_id] = [
                                'shopid'   => $store_id,
                                'shopname' => $company
                            ];
                        }

                        $class[$store_id]['pros'][] = call_user_func_array(function (ShoppingCart $shop) use (&$total) {
                            $shops['proid'] = $shop->goods_id;
                            $shops['href']  = route('goods.detail', [$shop->goods_id]);
                            $shops['img']   = $shop->goods->cover();
                            $shops['name']  = $shop->goods->name;
                            if ($shop->goods_spec_id) {
                                $shops['spec'] =
                                    GoodsSpecification::where('id', $shop->goods_spec_id)->first()->spec_first;
                            }
                            $shops['price']    =
                                sprintf("%.2f", $shop->goods->original_price * $shop->goods->getPriceStrategy());
                            $shops['num']      = $shop->amount;
                            $shops['subtotal'] = sprintf("%.2f", $shops['num'] * $shops['price']);

                            $total += ($shops['num'] * $shops['price']);

                            return $shops;
                        }, [$shop]);
                    }

                    return response()->json([
                        'data'           => array_values($class),
                        'total'          => sprintf("%.2f", $total),
                        'pagingConfData' => [
                            'page'     => $request->query('page'),
                            'pageSize' => $request->query('pageSize'),
                            'total'    => $count,
                        ],
                    ]);
                }
                return view('host/shopp/shoppingcart');
            } else {
                return view('host/shopp/emptyshoppingcart');
            }

        } catch (UserTypeException $e) {
            return redirect('error', '403');
            throw $e;
        }
    }

    /**
     * 更新购物车中的数量--单个增减
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function putUpdateInfo(Request $request)
    {

        $goods_id = (int)$request->input('goodid');
        $num      = (int)$request->input('buy_num');//修改的购物车中的数量
        if ($request->input('num') == 1) {  //增为 +  假为-
            //需要判断库存是否还有数据
            if (ShoppingCart::where('goods_id', $goods_id)->first()->amount < Goods::where('id',
                    $goods_id)->first()->stock
            ) {
                ShoppingCart::where('goods_id', $goods_id)->where('amount', '>=', '1')->increment('amount', 1);
            }

        } else {
            if ($request->input('num') == -1) {
                ShoppingCart::where('goods_id', $goods_id)->where('amount', '>', '1')->decrement('amount', 1);
            } else {
                ShoppingCart::where('goods_id', $goods_id)->update(['amount' => $num]);
            }
        }

        $member = \Auth::user();
        try {

            if (\Request::ajax()) {
                $shoppingList = ShoppingCart::where('member_id', $member->id)->get();
                $count        = ShoppingCart::where('member_id', $member->id)->count();

                $class = [];
                $total = 0;

                foreach ($shoppingList as $shop) {
                    //根据goods_id 查找store_id
                    $store_id = $shop->goods->store_id;

                    if (!isset($class[$store_id])) {
                        //根据store_id 查找店铺的名字
                        $company = MemberInformation::where('id',
                            Store::where('id', $store_id)->first()->member_id)->first()->company;

                        $class[$store_id] = [
                            'shopid'   => $store_id,
                            'shopname' => $company
                        ];
                    }

                    $class[$store_id]['pros'][] = call_user_func_array(function (ShoppingCart $shop) use (&$total) {
                        $shops['proid'] = $shop->goods_id;
                        $shops['img']   = $shop->goods->cover();
                        $shops['name']  = $shop->goods->name;
                        if ($shop->goods_spec_id) {
                            $shops['spec'] = GoodsSpecification::where('id', $shop->goods_spec_id)->first()->spec_first;
                        }
                        $shops['price']    =
                            sprintf("%.2f", $shop->goods->original_price * $shop->goods->getPriceStrategy());
                        $shops['num']      = $shop->amount;
                        $shops['subtotal'] = sprintf("%.2f", $shops['num'] * $shops['price']);

                        $total += ($shops['num'] * $shops['price']);

                        return $shops;
                    }, [$shop]);
                }

                return response()->json([
                    'data'           => array_values($class),
                    'total'          => sprintf("%.2f", $total),
                    'pagingConfData' => [
                        'page'     => $request->query('page'),
                        'pageSize' => $request->query('pageSize'),
                        'total'    => $count,
                    ],
                ]);
            }
            return view('host/shopp/shoppingcart');

        } catch (UserTypeException $e) {
            return redirect('error', '403');
            throw $e;
        }

    }


    /**
     * 随意更新购物车中的数量
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function putChangeCount(Request $request)
    {
        $goods_id = (int)$request->input('goodid');


        if ($num <= Goods::where('id', $goods_id)->first()->stock) {
            ShoppingCart::where('goods_id', $goods_id)->update(['amount' => $num]);
        }
        return $this->getCartList($request);
    }

    /**
     * 删除订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function deleteCartInfo(Request $request)
    {
        $goods_id = $request->input('goodid');
        ShoppingCart::where('goods_id', $goods_id)->delete();
        $member = \Auth::user();
        try {

            if (\Request::ajax()) {
                $shoppingList = ShoppingCart::where('member_id', $member->id)->get();
                $count        = ShoppingCart::where('member_id', $member->id)->count();

                $class = [];
                $total = 0;

                foreach ($shoppingList as $shop) {
                    //根据goods_id 查找store_id
                    $store_id = $shop->goods->store_id;

                    if (!isset($class[$store_id])) {
                        //根据store_id 查找店铺的名字
                        $company = MemberInformation::where('id',
                            Store::where('id', $store_id)->first()->member_id)->first()->company;

                        $class[$store_id] = [
                            'shopid'   => $store_id,
                            'shopname' => $company
                        ];
                    }

                    $class[$store_id]['pros'][] = call_user_func_array(function (ShoppingCart $shop) use (&$total) {
                        $shops['proid'] = $shop->goods_id;
                        $shops['img']   = $shop->goods->cover();
                        $shops['name']  = $shop->goods->name;
                        if ($shop->goods_spec_id) {
                            $shops['spec'] = GoodsSpecification::where('id', $shop->goods_spec_id)->first()->spec_first;
                        }
                        $shops['price']    =
                            sprintf("%.2f", $shop->goods->original_price * $shop->goods->getPriceStrategy());
                        $shops['num']      = $shop->amount;
                        $shops['subtotal'] = sprintf("%.2f", $shops['num'] * $shops['price']);

                        $total += ($shops['num'] * $shops['price']);

                        return $shops;
                    }, [$shop]);
                }

                return response()->json([
                    'data'           => array_values($class),
                    'total'          => sprintf("%.2f", $total),
                    'pagingConfData' => [
                        'page'     => $request->query('page'),
                        'pageSize' => $request->query('pageSize'),
                        'total'    => $count,
                    ],
                ]);
            }
            return view('host/shopp/shoppingcart');

        } catch (UserTypeException $e) {
            return redirect('error', '403');
            throw $e;
        }
    }
}

